import Vue from 'vue'
import { login, logout, phoneLogin, thirdLogin } from '@/api/login'
import {
  ACCESS_TOKEN,
  USER_NAME,
  USER_INFO,
  USER_AUTH,
  SYS_BUTTON_AUTH,
  UI_CACHE_DB_DICT_DATA,
  TENANT_ID,
  CACHE_INCLUDED_ROUTES
} from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { queryPermissionsByUser } from '@/api/api'
import { getAction } from '@/api/manage'

// import { USERINFO, USERNAME, PASSWORD, PHONE_NUMBER, ACCESS_TOKEN } from '@/store/mutation-types'

import {
  generateSaltRequest,
  getSaltRequest,
  signInRequest,
  signOutRequest,
  signUpRequest,
  validateUsernameRequest,
  getUserInfoRequest,
  updateUserInfoRequest,
  sendCaptchaRequest,
  updateAccountInfoRequest,
  getImageCaptchaRequest
} from '@/api/user'

const user = {
  namespaced: true,
  state: {
    oldSalt: undefined,
    salt: undefined,
    token: '',
    username: '',
    realname: '',
    tenantid: '',
    welcome: '',
    avatar: '',
    permissionList: [],
    captchaCheckKey: '',
    imageCaptcha: '',
    info: {},
    // 系统安全模式
    sysSafeMode: null,

  },

  mutations: {
    SET_OLD_SALT: (state, oldSalt) => {
      state.oldSalt = oldSalt
    },

    SET_SALT: (state, salt) => {
      state.salt = salt
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username, realname, welcome }) => {
      state.username = username
      state.realname = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_TENANT: (state, id) => {
      state.tenantid = id
    },

    SET_CAPTCHA_CHECK_KEY: (state, captchaCheckKey) => {
      state.captchaCheckKey = captchaCheckKey
    },
    SET_IMAGE_CAPTCHA: (state, imageCaptcha) => {
      state.imageCaptcha = imageCaptcha
    },
    SET_SYS_SAFE_MODE: (state, sysSafeMode) => {
      if (typeof sysSafeMode === 'boolean') {
        state.sysSafeMode = sysSafeMode
      } else {
        state.sysSafeMode = false
      }
    }

  },

  actions: {
    generateSaltAction({ commit }, parameters) {
      return new Promise((resolve, reject) => {
        generateSaltRequest(parameters)
          .then(response => {
            if (response && response.success && response.result) {
              const oldSalt = response.result.oldSalt
              const salt = response.result.salt
              if (salt) {
                commit('SET_SALT', salt)
              }
              if (oldSalt) {
                commit('SET_OLD_SALT', oldSalt)
              }
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    getSaltAction({ commit }, parameters) {
      return new Promise((resolve, reject) => {
        getSaltRequest(parameters)
          .then(response => {
            if (response && response.success && response.result) {
              const salt = response.result.salt
              if (salt) {
                commit('SET_SALT', salt)
              }

              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // CAS验证登录
    ValidateLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        getAction('/sys/cas/client/validateLogin', userInfo)
          .then(response => {
            console.log('----cas 登录--------', response)
            if (response.success) {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('user/SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              resolve(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 手机号登录
    PhoneLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        phoneLogin(userInfo)
          .then(response => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    getImageCaptchaAction({ commit }, parameters) {
      return new Promise((resolve, reject) => {
        const captchaCheckKey = new Date().getTime()
        commit('SET_CAPTCHA_CHECK_KEY', captchaCheckKey)
        getImageCaptchaRequest(captchaCheckKey)
          .then(response => {
            if (response && response.success) {
              const imageCaptcha = response.result
              commit('SET_IMAGE_CAPTCHA', imageCaptcha)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetPermissionList({ commit }) {
      return new Promise((resolve, reject) => {
        queryPermissionsByUser().then(response => {

          // update-begin----author:scott---date:20221018------for: 判断是否是 vue3 版本的菜单，给予提示 ---
          let routeList = response.result.menu;
          var findVue3Menu = routeList.find(item => {
            return item.component === 'layouts/default/index';
          });
          if (findVue3Menu) {
            console.error("启动失败: 检查到当前菜单表是Vue3版本，导致菜单加载异常，请切换到Vue2版菜单！参考：http://doc.jeecg.com/3075165")
            Vue.prototype.$Jmessage.error('启动失败: 检查到当前菜单表是Vue3版本，导致菜单加载异常，请切换到Vue2版菜单！参考：http://doc.jeecg.com/3075165', 0)
          }
          // update-end----author:scott---date:20221018------for: 判断是否是 vue3 版本的菜单，给予提示 ---


          const menuData = response.result.menu;
          const authData = response.result.auth;
          const allAuthData = response.result.allAuth;
          //Vue.ls.set(USER_AUTH,authData);
          sessionStorage.setItem(USER_AUTH, JSON.stringify(authData));
          sessionStorage.setItem(SYS_BUTTON_AUTH, JSON.stringify(allAuthData));
          if (menuData && menuData.length > 0) {
            // //update--begin--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
            // menuData.forEach((item, index) => {
            //   if (item["children"]) {
            //     let hasChildrenMenu = item["children"].filter((i) => {
            //       return !i.hidden || i.hidden == false
            //     })
            //     if (hasChildrenMenu == null || hasChildrenMenu.length == 0) {
            //       item["hidden"] = true
            //     }
            //   }
            // })
            // //console.log(" menu show json ", menuData)
            // //update--end--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
            commit('SET_PERMISSIONLIST', menuData)
            // 设置系统安全模式
            commit('SET_SYS_SAFE_MODE', response.result.sysSafeMode)
          } else {
            reject('getPermissionList: permissions must be a non-null array !')
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },



    // 登出
    Logout({ commit, state }) {
      return new Promise(resolve => {
        let logoutToken = state.token
        commit('SET_TOKEN', '')
        commit('SET_PERMISSIONLIST', [])
        Vue.ls.remove(ACCESS_TOKEN)
        Vue.ls.remove(USER_INFO)
        Vue.ls.remove(USER_NAME)
        Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
        Vue.ls.remove(CACHE_INCLUDED_ROUTES)
        // console.log('logoutToken: '+ logoutToken)
        logout(logoutToken)
          .then(() => {
            if (process.env.VUE_APP_SSO == 'true') {
              let sevice = 'http://' + window.location.host + '/'
              let serviceUrl = encodeURIComponent(sevice)
              window.location.href = process.env.VUE_APP_CAS_BASE_URL + '/logout?service=' + serviceUrl
            }
            resolve()
          })
          .catch(() => {
            resolve()
          })
      })
    },
    // 第三方登录
    ThirdLogin({ commit }, param) {
      return new Promise((resolve, reject) => {
        thirdLogin(param.token, param.thirdType)
          .then(response => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    saveTenant({ commit }, id) {
      Vue.ls.set(TENANT_ID, id, 7 * 24 * 60 * 60 * 1000)
      commit('SET_TENANT', id)
    },
    signIn({ commit }, parameters) {
      return new Promise((resolve, reject) => {
        signInRequest(parameters)
          .then(response => {
            console.log('\n\n  = ' + JSON.stringify(response) + '\n\n')
            if (response && response.success && response.result && response.result.userInfo) {
              const info = response.result.userInfo
              const token = response.result.token

              Vue.ls.set(ACCESS_TOKEN, token, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', token)
              commit('SET_INFO', info)
              console.log('\nSET_INFO token = ' + JSON.stringify(token) + '\n\n')
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    signOut({ commit }, parameters) {
      return new Promise((resolve, reject) => {
        signOutRequest(parameters)
          .then(response => {
            if (response.success) {
              commit('user/SET_TOKEN', '')
              commit('SET_INFO', null)

              Vue.ls.remove(ACCESS_TOKEN)
              Vue.ls.remove(USERINFO)

              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    signUp({ commit }, parameters) {
      console.log('\n\nsignUp  = ' + JSON.stringify(parameters) + '\n\n')
      return new Promise((resolve, reject) => {
        console.log('\n\n signUp = ' + 'signUp' + '\n\n')
        signUpRequest(parameters)
          .then(response => {
            if (response && response.success) {
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            console.log('\n\n error = ' + JSON.stringify(error) + '\n\n')
            reject(error)
          })
      })
    },

    // eslint-disable-next-line no-unused-vars
    validateUsername({ commit }, parameters) {
      return new Promise((resolve, reject) => {
        validateUsernameRequest(parameters)
          .then(response => {
            if (response && response.result && response.result.isSignedUp) {
              resolve(response.result.isSignedUp)
            } else {
              resolve(false)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // eslint-disable-next-line no-unused-vars
    updateAccountInfoAction({ commit }, parameters) {
      return new Promise((resolve, reject) => {
        updateAccountInfoRequest(parameters)
          .then(response => {
            if (response && response.success) {
              resolve(response)
            } else {
              resolve(false)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    GetUserInfo({ commit }, parameters) {
      return new Promise((resolve, reject) => {
        getUserInfoRequest(parameters)
          .then(response => {
            const info = response.result
            commit('SET_INFO', info)
            console.log('\n\n response = ' + JSON.stringify(response) + '\n\n')
            if (response && response.result) {
              const info = response.result
              commit('SET_INFO', info)
              resolve(response.success)
            } else {
              resolve(false)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  }
}

export default user

